<!--
 * @Date: 2024-09-12 10:50:41
 * @Author: Yu Weifeng weifeng.yu@gientech.com
 * @Description: 散点图
-->
<template>
  <ChartBase :options="chartOptions" :currentEcharts="echarts" class="lc-chart__scatter" />
</template>
<script setup>
import { chartProps } from '../base.ts';
import { computed } from 'vue';
import ChartBase from '../base.vue';
import { isEmpty, isObject } from 'lodash-es';
import * as echarts from 'echarts/core';
import {
  TitleComponent,
  DatasetComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BrushComponent,
  MarkLineComponent,
  MarkAreaComponent,
  MarkPointComponent
} from 'echarts/components';
import { ScatterChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
  TitleComponent,
  DatasetComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BrushComponent,
  MarkLineComponent,
  MarkAreaComponent,
  MarkPointComponent,
  ScatterChart,
  CanvasRenderer,
  UniversalTransition
]);

defineOptions({
  name: 'LcChartScatter'
});
const props = defineProps(chartProps);

const processData = (data, mapOptions) => {
  if (data.length) {
    let transformData = [];
    // 设置了映射字段 或者 数据里有name和value字段
    if (!isEmpty(mapOptions) || (isObject(data[0]) && data[0]['name'] && data[0]['value'])) {
      if ((mapOptions && mapOptions.type) || data[0]['type']) {
        const groupData = {};
        data.forEach((item) => {
          //分组
          const groupType = item[mapOptions?.type || 'type'];
          groupData[groupType] = groupData[groupType] ?? [];
          groupData[groupType].push([
            item[mapOptions?.dimension || 'name'],
            item[mapOptions?.valueMap || 'value']
          ]);
        });
        Object.keys(groupData).forEach((group) => {
          transformData.push({ name: group, value: groupData[group] });
        });
      } else {
        let tempValues = [];
        data.forEach((item) => {
          tempValues.push([
            item[mapOptions?.dimension || 'name'],
            item[mapOptions?.valueMap || 'value']
          ]);
        });
        transformData.push({ name: '', value: tempValues });
      }
    } else {
      transformData = data;
    }
    return transformData;
  } else {
    return [];
  }
};
const chartOptions = computed(() => {
  const options = props.options;
  const processedData = processData(props.data, props.mapOptions);
  const series = processedData.map((data) => ({
    name: data.name,
    ...options.series,
    data: data.value
  }));
  options.series = series;
  return options;
});
</script>
